package com.easychat.websocket;

import com.alibaba.fastjson.JSON;
import com.easychat.entity.dto.MessageSendDto;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @program: easychat-java
 * @description: 消息处理器
 * @author: Mr.Wang
 * @create: 2024-12-11 19:47
 **/
@Component("messageHandler")
public class MessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(MessageHandler.class);

    private static final String MESSAGE_TOPIC = "message.topic";
    @Resource
    private RedissonClient redissonClient;

    @Resource
    private ChannelContextUtils channelContextUtils;

    @PostConstruct
    public void lisMessage(){
        logger.info("开始监听消息");
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        rTopic.addListener(MessageSendDto.class,(MessageSendDto,sendDto)->{
            logger.info("收到广播消息:{}", JSON.toJSONString(sendDto));
            channelContextUtils.sendMessage(sendDto);
        });
    }
    public void sendMessage(MessageSendDto sendDto){
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        logger.info("发布消息");
        channelContextUtils.sendMessage(sendDto);
//        rTopic.publish(sendDto);
    }

}
